package com.playball.lottery.frm.kjinfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.JddMainActivity;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.PullDownView;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.customview.PullDownView.OnPullDownListener;
import com.playball.lottery.frm.buyhall.BDActivity;
import com.playball.lottery.nt.orjdd.GetRequestParams;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.SysApplication;


/**
 * 北单开奖信息
 * 
 * @author Administrator
 * 
 */
public class KjinfoBDResult extends BaseActivity implements OnPullDownListener {
	/** 上下文内容 */
	private Context context = null;
	private TextView timeText;
	private RelativeLayout btnSelTime;
	private LinearLayout btnSelWanfa;
	private List<Map<String, Object>> mData;
	/** 赛事期次数组对应下标 */
	private int issueIndex = -1;
	/** 期次ID */
	String[] issuesID = new String[10];
	/** 期次名，表现形式为数字 */
	String[] issuesName;// String[] issuesName = new String[10];
	/** 进度listview视图 */
	private ListView kjinfo_lv;
	/** 自定义下拉刷新组件 **/
	private PullDownView mPullDownView;
	/** 网络获取的数据 */
	private List<Map<String, Object>> netDataList;
	/** 请求第几页数据 */
	private int intPageNo = 1;// 0
	/** 是否有下一页 */
	private boolean nextPage = false;
	/** 是否按更多 */
	private boolean isPressMore = false;
	/** 开奖适配器 */
	private KjInfoListAdapter adapter;
	/** 记录总条数 */
	private int intTotalNum;
	/** 一页显示数 */
	private int pageSize = 10;
	/** 是否已经获取数据 */
	private boolean isGetData = false;
	Button kjinfo_btn_totouzhu;
	private int issuesId = 0;

	/** 判断是否从推送通知过来 */
	private Boolean ifPush;
	/** 判断是否哪个彩种ID通知过来 */
	private String isLottID;
	/** 判断是否从哪个彩种名通知过来 */
	private String isLottName;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.context = this;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.kjinfo_info_match);
		SysApplication.getInstance().addActivity(this);
		ifPush = getIntent().getBooleanExtra("ifPush", false);
		isLottID=getIntent().getStringExtra("LottID");
		isLottName=getIntent().getStringExtra("LottName");
		initView();
		titleBar();
		isGetData = false;
		// // 启动查询赛果线程
		// AsyncLoaderIssueInfo asyncLoaderIssueInfo = new
		// AsyncLoaderIssueInfo();
		// asyncLoaderIssueInfo.execute("lott/bjdc/result.js");
		// 时间按钮监听
		btnSelTime.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (isGetData) {// 只有已经从网络获取期次信息，才能选择期次
					Dialog dialog = null;
					Builder builder = new AlertDialog.Builder(KjinfoBDResult.this);
					builder.setTitle(getString(R.string.kjinfo_match_selissue));
					// builder.setIcon(R.drawable.basketball);
					DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							if (which >= 0) {
								issueIndex = which;
								timeText.setText(issuesName[issueIndex]);
								issuesId = (Integer) issueData.get(which).get("ID");
								dialog.dismiss();
								// 每次重新选择日期组件时需要从第一页开始查询
								intPageNo = 1;
								startMatchThread();
							}
						}
					};
					builder.setSingleChoiceItems(issuesName, issueIndex, onClickListener);
					dialog = builder.create();
					dialog.show();
				}
			}
		});

		kjinfo_btn_totouzhu.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(KjinfoBDResult.this, BDActivity.class);
				startActivity(intent);
			}
		});

		new KjinfoBDLoader().execute("");
	}

	public void onResume() {
		super.onResume();
		
	}

	public void onPause() {
		super.onPause();
		
	}

	private void initView() {
		timeText = (TextView) findViewById(R.id.kjinfo_match_date);
		btnSelTime = (RelativeLayout) findViewById(R.id.kjinfo_match_seldate_rl);
		btnSelWanfa = (LinearLayout) findViewById(R.id.kjinfo_match_selwanfa_ll);
		btnSelWanfa.setVisibility(View.GONE);
		View kjinfo_match_selwanfa_lline = (View) findViewById(R.id.kjinfo_match_selwanfa_lline);
		kjinfo_match_selwanfa_lline.setVisibility(View.GONE);
		kjinfo_btn_totouzhu = (Button) findViewById(R.id.kjinfo_btn_totouzhu);
		timeText.setText("------");

		/*
		 * 1.使用PullDownView 2.设置OnPullDownListener 3.从mPullDownView里面获取ListView
		 */
		mPullDownView = (PullDownView) findViewById(R.id.kjinfo_lv);

		mPullDownView.setOnPullDownListener(this);

		kjinfo_lv = mPullDownView.getListView();

	}

	// 启动查询赛果线程
	private void startMatchThread() {
		// String mTime = timeText.getText().toString();
		// AsyncLoaderIssueDetail asyncLoaderIssueDetail = new
		// AsyncLoaderIssueDetail();
		// asyncLoaderIssueDetail.execute(new String[] { mTime, (intPageNo - 1)
		// + "" });
		new KjinfoBDLoader().execute("");
	}

	/**
	 * 处理网络数据，按listview字段分别适应加载到SimpleAdapter
	 */
	public List<Map<String, Object>> modifymData(List<Map<String, Object>> list) {
		if (list != null && list.size() != 0) {
			List<Map<String, Object>> NewList = new ArrayList<Map<String, Object>>();
			for (int i = 0; i < list.size(); i++) {
				// {
				// "IssueNo": "1",
				// "Wk": "0",
				// "MName": "天皇杯",
				// "HTeam": "大分三神",
				// "VTeam": "横滨水手",
				// "MTime": "2013/12/22 12:00:00",
				// "ETime": "2013/12/22 11:45:00",
				// "Rq": "1",
				// "BgColor": "#29197B",
				// "HRz": "0:0",
				// "Rz": "1:1",
				// "RZResult": "3,2,0,11,11",
				// "SPResult": "2.799797,4.252552,2.961786,9.910999,7.565993"
				// },
				Map<String, Object> OldMap = list.get(i);
				Map<String, Object> NewMap = new HashMap<String, Object>();
				String strCg;
				String Cg = null;
				String rzString = null;
				String json = OldMap.get("Cg").toString();
				try {
					JSONObject jsonObject = new JSONObject(json);
					rzString = jsonObject.getString("RZ");
					// spString = jsonObject.getString("SP");
				} catch (JSONException e) {
					e.printStackTrace();
				}

				strCg = String.valueOf(rzString);
				if ("".equals(strCg)) {
					Cg = "-";
				} else {
					String Cg0 = strCg.split(",")[0];
					if (Cg0.equals("3")) {
						Cg = "胜";
					} else if (Cg0.equals("1")) {
						Cg = "平";
					} else if (Cg0.equals("0")) {
						Cg = "负";
					}
				}
				// "MNo", "NMm", "HTeam", "Rq", "VTeam", "Score", "Cg"
				NewMap.put("MNo", OldMap.get("MNo"));
				NewMap.put("NMm", OldMap.get("NMm"));
				NewMap.put("HTeam", OldMap.get("HTeam"));
				String rq = OldMap.get("Rq").toString();
				if (TextUtils.isEmpty(rq)) {
					rq = "-";
				}
				NewMap.put("Rq", rq);
				NewMap.put("VTeam", OldMap.get("VTeam"));
				String score = OldMap.get("Score").toString().replaceAll(":", "-");
				if (TextUtils.isEmpty(score)) {
					score = "-";
				}
				NewMap.put("Score", score);
				NewMap.put("Cg", Cg);
				NewList.add(NewMap);
			}
			return NewList;
		}
		return null;
	}

	/**
	 * 放入数据，显示listview视图
	 */
	public void showKList() {
		// //获取更多数据之外的请求，如首次请求数据，
		if (!isPressMore) {
			// 填充UI,listview
			mData = modifymData(netDataList);
			if (mData != null) {
				adapter = new KjInfoListAdapter(KjinfoBDResult.this, mData);
				kjinfo_lv.setAdapter(adapter);
			}
			// 隐藏并且禁用头部刷新
			mPullDownView.setHideHeader();
			// 显示并且可以使用头部刷新
			// mPullDownView.setShowHeader();
			/** 关闭 刷新完毕 ***/
			// mPullDownView.RefreshComplete();// 这个事线程安全的 可看源代码

		} else {
			// 获取更多数据
			List<Map<String, Object>> tData = new ArrayList<Map<String, Object>>();
			tData = modifymData(netDataList);
			mData.addAll(tData);
			adapter.notifyDataSetChanged();
		}
		// 判断是否有下一页
		if (nextPage) {
			// 显示并启用自动获取更多
			mPullDownView.setShowFooter();
			// 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
			mPullDownView.enableAutoFetchMore(true, 1);
		} else {
			// 隐藏 并禁用尾部
			mPullDownView.setHideFooter();
			// 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
			mPullDownView.enableAutoFetchMore(false, 1);
		}
		// 告诉它获取更多完毕 这个事线程安全的 可看源代码
		mPullDownView.notifyDidMore();

		isPressMore = false;

	}

	/**
	 * listview刷新
	 */
	public void onRefresh() {

	}

	/**
	 * listview更多
	 */
	public void onMore() {
		isPressMore = true;
		// 发送更多请求
		intPageNo++;
		startMatchThread();
	}

	class KjInfoListAdapter extends BaseAdapter {

		private LayoutInflater inflater = null;

		private List<Map<String, Object>> mData;

		public KjInfoListAdapter(Context context, List<Map<String, Object>> mData) {
			inflater = LayoutInflater.from(context);
			this.mData = mData;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			// int lotIdInt = Integer.parseInt(lottID);
			ViewHolder holder = null;
			holder = new ViewHolder();

			LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			layoutParams.gravity = Gravity.CENTER_VERTICAL;

			try {
				convertView = inflater.inflate(R.layout.kjinfo_info_match_list, null);
				holder.kjinfo_match_list_mno = (TextView) convertView.findViewById(R.id.kjinfo_match_list_mno);
				holder.kjinfo_match_list_mnm = (TextView) convertView.findViewById(R.id.kjinfo_match_list_mnm);
				holder.kjinfo_match_list_hteam = (TextView) convertView.findViewById(R.id.kjinfo_match_list_hteam);
				holder.kjinfo_match_list_rq = (TextView) convertView.findViewById(R.id.kjinfo_match_list_rq);
				holder.kjinfo_match_list_vteam = (TextView) convertView.findViewById(R.id.kjinfo_match_list_vteam);
				holder.kjinfo_match_list_score = (TextView) convertView.findViewById(R.id.kjinfo_match_list_score);
				holder.kjinfo_match_list_cg = (TextView) convertView.findViewById(R.id.kjinfo_match_list_cg);
				holder.kjinfo_match_list_mno.setText(mData.get(position).get("MNo").toString());
				holder.kjinfo_match_list_mnm.setText(mData.get(position).get("NMm").toString());
				// holder.kjinfo_match_list_hteam.setText(mData.get(position).get("HTeam").toString());
				// holder.kjinfo_match_list_rq.setText(mData.get(position).get("Rq").toString());
				holder.kjinfo_match_list_hteam.setText(mData.get(position).get("HTeam").toString() + "("
						+ mData.get(position).get("Rq").toString() + ")");
				holder.kjinfo_match_list_vteam.setText(mData.get(position).get("VTeam").toString());
				holder.kjinfo_match_list_score.setText(mData.get(position).get("Score").toString());
				if (mData.get(position).get("Cg").toString().equals("胜")) {
					holder.kjinfo_match_list_cg.setBackgroundColor(context.getResources().getColor(
							R.color.ui_txt_color_selected_red));
					// holder.kjinfo_match_list_score.setTextColor(context
					// .getResources().getColor(
					// R.color.kjinfo_detail_ftbg_qianhong));
				} else if (mData.get(position).get("Cg").toString().equals("平")) {
					holder.kjinfo_match_list_cg.setBackgroundColor(context.getResources().getColor(
							R.color.ui_new_divider_bg));
					// holder.kjinfo_match_list_score.setTextColor(context
					// .getResources().getColor(
					// R.color.kjinfo_detail_ftbg_qianlan));
				} else if (mData.get(position).get("Cg").toString().equals("负")) {
					holder.kjinfo_match_list_cg.setBackgroundColor(context.getResources().getColor(
							R.color.ui_new_btn_no_normal_solid));
					// holder.kjinfo_match_list_score.setTextColor(context
					// .getResources().getColor(
					// R.color.kjinfo_detail_ftbg_qianlv));
				}
				holder.kjinfo_match_list_cg.setText(mData.get(position).get("Cg").toString());

				convertView.setTag(holder);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}

			return convertView;
		}

		class ViewHolder {
			TextView kjinfo_match_list_mno;
			TextView kjinfo_match_list_mnm;
			TextView kjinfo_match_list_hteam;
			TextView kjinfo_match_list_rq;
			TextView kjinfo_match_list_vteam;
			TextView kjinfo_match_list_score;// 比分
			TextView kjinfo_match_list_cg;// 赛果
		}
	}

	// titleBar标题栏
	public void titleBar() {
		// Title信息(返回+Title)
		Button back = (Button) findViewById(R.id.top_title_back);
		// back.getBackground().setAlpha(255);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onKeyDown(KeyEvent.KEYCODE_BACK, null);

			}
		});

		TextView info = (TextView) findViewById(R.id.top_title_info);
		info.setText(isLottName+"开奖");

		Button refres = (Button) findViewById(R.id.top_title_refres);
		refres.getBackground().setAlpha(255);
		refres.setVisibility(View.INVISIBLE);
		refres.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// not event

			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(ifPush){
				Intent intent = new Intent(this, JddMainActivity.class);
				startActivity(intent);
			}
			this.finish();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}

	};

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		SysApplication.getInstance().removeActivity(this);
	};

	// class AsyncLoaderIssueInfo extends AsyncTask<String, integer, String> {
	//
	// @Override
	// protected String doInBackground(String... params) {
	// // TODO Auto-generated method stub
	// return GetJsonData.getContent("lott/bjdc/result.js", true);
	// }
	//
	// @Override
	// protected void onPostExecute(String result) {
	// // TODO Auto-generated method stub
	// isGetData = true;
	// result = result.replaceAll("var data=", "");
	// issueData = ConvertJsonToList.getList(result);
	// issueIndex = 0;
	// timeText.setText(issueData.get(issueIndex).get("Name").toString());
	// intTotalNum =
	// Integer.valueOf(issueData.get(issueIndex).get("Count").toString());
	// issuesName = new String[issueData.size()];
	// for (int i = 0; i < issueData.size(); i++) {
	// issuesName[i] = issueData.get(i).get("Name").toString().trim();
	// }
	// intPageNo = 1;
	// issueIndex = 0;
	// // 启动查询赛果线程
	// startMatchThread();
	// }
	// }

	/*
	 * class AsyncLoaderIssueDetail extends AsyncTask<String, integer, String> {
	 * 
	 * @Override protected String doInBackground(String... params) { // TODO
	 * Auto-generated method stub boolean isExist = false; for (int i = 0; i <
	 * issueData.size() && isExist != true; i++) { if
	 * (TextUtils.equals(issueData.get(i).get("Name").toString().trim(),
	 * params[0])) { issueIndex = i; isExist = true; } } if (isExist == true) {
	 * return GetJsonData.getContent("/lott/bjdc/match/" + params[0] + "/" +
	 * params[1] + ".js", true); } else { return null; } }
	 * 
	 * @Override protected void onPostExecute(String result) { // TODO
	 * Auto-generated method stub if (result != null) { result =
	 * result.replaceAll("var data=", ""); netDataList =
	 * ConvertJsonToList.getList(result); if (intPageNo * pageSize >=
	 * intTotalNum) { nextPage = false; } else { nextPage = true; } showKList();
	 * } else {
	 * 
	 * }
	 * 
	 * } }
	 */

	List<Map<String, Object>> issueData = null;

	private class KjinfoBDLoader extends AsyncTask<Object, Integer, String> {
		ShowTipDialog showdialog = new ShowTipDialog();

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			showdialog.showDialog(KjinfoBDResult.this);
		}

		@Override
		protected String doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String strResult;

			JSONObject jsob = new JSONObject();
			try {
				jsob.put("LottID",isLottID);
				jsob.put("IssueID", issuesId);
				jsob.put("PageNo", intPageNo);
				jsob.put("PageSize", 10);
			} catch (JSONException ex) {
			}
			String parms = jsob.toString();
			String action = "312";

			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(parms, UserID, action, getApplicationContext());
			return strResult;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			try {
				if (null != result) {

					System.out.println("=======" + result);

					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					if (js.getInt("Code") == 0) {
						isGetData = true;
						JSONObject object = new JSONObject(js.getString("Data"));
						if (issuesId == 0) {
							issueData = ConvertJsonToList.getList(object.getString("Issues"));
							issueIndex = 0;
							timeText.setText(issueData.get(issueIndex).get("Name").toString());
							issuesName = new String[issueData.size()];
							for (int i = 0; i < issueData.size(); i++) {
								issuesName[i] = issueData.get(i).get("Name").toString().trim();
							}
						}
						intTotalNum = object.getInt("Count");

						netDataList = ConvertJsonToList.getList(object.getString("item"));
						if (intPageNo * pageSize >= intTotalNum) {
							nextPage = false;
						} else {
							nextPage = true;
						}
						showKList();
					} else {

					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} finally {
				showdialog.closeDialog();
			}
		}

	}

}
